package com.ljl.forum_1.controller;

import com.ljl.forum_1.common.AppResult;
import com.ljl.forum_1.common.ResultCode;
import com.ljl.forum_1.exception.ApplicationException;
import com.ljl.forum_1.model.Board;
import com.ljl.forum_1.services.IBoradService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Keafmd
 *
 * @ClassName: BoardController
 * @Description: BoardController
 * @author: lijl
 * @date: 2025/2/8 13:52
 * @Blog: https://keafmd.blog.csdn.net/
 */
@Slf4j
@Api(tags = "板块接口")
@RestController
@RequestMapping("/board")
public class BoardController {

    // 从配置文件中读取值，如果没有配置，默认值为2
    @Value("${forum.index.board-num:2}")
    private Integer indexBoardNum;

    @Resource
    private IBoradService boradService;

    // 查询首页板块列表
    @ApiOperation("获取首页板块列表")
    @GetMapping("/topList")
    public AppResult<List<Board>> topList() {
        log.info("首页板块个数为：" + indexBoardNum);
        // 调用service查询结果
        List<Board> boards = boradService.selectByNum(indexBoardNum);
        // 判断是否为空
        if(boards == null) {
            boards = new ArrayList<>();
        }
        // 返回结果
        return AppResult.success(boards);
    }

    @ApiOperation("根据版块id获取板块信息")
    @GetMapping("/getById")
    public AppResult<Board> getById(@ApiParam("板块ID") @RequestParam("id") @NonNull Long id) {
        // 调用service
        Board board = boradService.selectById(id);

        // 校验版块是否存在或是否已删除
        if (board == null || board.getDeleteState() == 1) {
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }

        // 返回结果
        return AppResult.success(board);
    }
}
